<template>
    <div>
        <!-- 新增与搜索区域 -->
        <div class="header-actions">
            <el-button @click="showAddDialog">新增试卷</el-button>
            <el-input v-model="searchQuery" placeholder="搜索试卷..." style="width: 200px;" />
        </div>
        
        <!-- 添加表格容器ref -->
        <div ref="tableContainer">
            <el-table :data="filteredPapers" border style="width: 100%">
                <el-table-column prop="id" label="ID"></el-table-column>
                <el-table-column prop="name" label="试卷名称"></el-table-column>
                <el-table-column prop="totalScore" label="总分"></el-table-column>
                <el-table-column prop="passScore" label="及格线"></el-table-column>

                <el-table-column prop="createTime" label="创建时间">
                    <template #default="{ row }">
                        {{ formatTime(row.createTime) }}
                    </template>
                </el-table-column>

                <!-- 操作列 -->
                <el-table-column label="操作">
                    <template #default="{ row }">
                        <el-button size="small" type="success" @click="$router.push(`/papers/${row.id}`)">查看详情</el-button>
                        <el-button size="small" type="danger" @click="deletePaper(row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 新增试卷对话框 -->
        <el-dialog v-model="dialogVisible" title="新增试卷"  style="width: 500px;">
            <el-form :model="newPaperForm" label-width="120px">
                <el-form-item label="试卷名称">
                    <el-input v-model="newPaperForm.name" placeholder="请输入试卷名称" />
                </el-form-item>

                <el-form-item label="选择规则">
                    <el-select v-model="newPaperForm.ruleId" placeholder="请选择规则" style="width: 100%">
                        <el-option v-for="rule in rules" :key="rule.id" :label="rule.name" :value="rule.id" />
                    </el-select>
                </el-form-item>

                <el-form-item label="总分">
                    <el-input v-model.number="newPaperForm.totalScore" disabled />
                </el-form-item>

                <el-form-item label="及格线">
                    <el-input v-model.number="newPaperForm.passScore" placeholder="请输入及格线" disabled />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitAddPaper">提交</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue';
import api from '../services/api';
import { ElLoading, ElMessageBox, ElMessage } from 'element-plus';

const papers = ref([]);
const dialogVisible = ref(false);
const newPaperForm = ref({
    name: '',
    ruleId: null,
    totalScore: 0,
    passScore: 0,
    createTime: new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60000).toISOString(),
});
const rules = ref([]);
const searchQuery = ref('');

// 过滤后的试卷列表用于显示
const filteredPapers = computed(() => {
    const keyword = searchQuery.value.trim().toLowerCase();
    if (!keyword) return papers.value;

    return papers.value.filter(paper =>
        paper.name?.toLowerCase().includes(keyword) ||
        String(paper.id).includes(keyword)
    );
});

// 当选择的规则变化时，自动填充总分
watch(
    () => newPaperForm.value.ruleId,
    (ruleId) => {
        if (ruleId) {
            const selectedRule = rules.value.find(r => r.id === ruleId);
            if (selectedRule) {
                newPaperForm.value.totalScore = selectedRule.totalScore;
                // 如果没有设置及格线，则默认设置为总分的60%
                if (!newPaperForm.value.passScore || newPaperForm.value.passScore === 0) {
                    newPaperForm.value.passScore = Math.round(selectedRule.totalScore * 0.6);
                }
            }
        }
    }
);

async function fetchPapers() {
    const res = await api.getAllPapers();
    papers.value = res.data;
}

async function fetchRules() {
    const res = await api.getRules();
    rules.value = res.data;
}

function formatTime(timeStr) {
    const date = new Date(timeStr);
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
}

async function deletePaper(id) {
  try {
    await ElMessageBox.confirm('确定删除该试卷？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await api.deletePaper(id);
    fetchPapers();
    ElMessage.success('试卷删除成功');
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('试卷删除失败');
    }
  }
}

function showAddDialog() {
    dialogVisible.value = true;
}

async function submitAddPaper() {
    try {
        await api.createPaper(newPaperForm.value);
        dialogVisible.value = false;
        // 重置表单
        newPaperForm.value = {
            name: '',
            ruleId: null,
            totalScore: 0,
            passScore: 0,
            createTime: new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60000).toISOString(),
        };
        // 刷新试卷列表
        fetchPapers();
        ElMessage.success('试卷新增成功');
    } catch (error) {
        console.error('新增试卷失败:', error);
        ElMessage.error('试卷新增失败');
    }
}

const tableContainer = ref(null);  // 添加表格容器ref

onMounted(async () => {
  const loading = ElLoading.service({
    lock: false,  // 关闭全屏锁定
    target: tableContainer.value,  // 指定目标容器
    text: '数据加载中',
    background: 'rgba(0, 0, 0, 0.3)'
  });

  try {
    await Promise.all([fetchRules(), fetchPapers()]);
    setTimeout(() => loading.close(), 500);
  } catch (error) {
    loading.close();
    console.error('初始化数据失败:', error);
  }
});
</script>